/*
 * MathProcesses.cpp
 *
 *  Created on: Feb 14, 2012
 *      Author: nhatuan
 */

#include "MathProcesses.h"
#include <stdio.h>

/**
 * calculate the covariance matrix of two features
 */
float ** calculateCovarianceMatrix(float* x, float *y, float xm, float ym, int length) {
	float **returnArray = new float*[2];
	for (int i=0; i<2; i++) {
		returnArray[i] = new float[2];
	}
	for (int i=0; i<2; i++) {
		for (int j=0; j<2; j++)
			returnArray[i][j] = 0;
	}
	for(int i=0; i<length; i++) {
		returnArray[0][0] += pow((x[i] - xm), 2);
		returnArray[1][1] += pow((y[i] - ym), 2);
		returnArray[0][1] += (x[i] - xm) * (y[i] - ym);
		returnArray[1][0] += (x[i] - xm) * (y[i] - ym);
	}

	returnArray[0][0] /= length;
	returnArray[0][1] /= length;
	returnArray[1][0] /= length;
	returnArray[1][1] /= length;

	return returnArray;
}

/**
 * calculate the correlation matrix of two features
 */
float ** calculateCorrelationMatrix(float *x, float *y, float xm, float ym, int length) {
	float ** returnArray = calculateCovarianceMatrix(x, y, xm, ym, length);
	float a = sqrt(returnArray[0][0]);
	float b = sqrt(returnArray[1][1]);
	returnArray[0][0] /= a * a;
	returnArray[1][1] /= b * b;
	returnArray[1][0] /= a * b;
	returnArray[0][1] /= b * a;

	return returnArray;
}

float calculateDeterminant(float ** matrix) {
	return (float) matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix [1][0];
}

float ** calculateInverseMatrix(float ** matrix){
	float determinant = calculateDeterminant(matrix);
	if (determinant == 0) throw "division by zero";
	float factor = 1 / determinant;

	float **returnArray = new float*[2];
	for (int i=0; i<2; i++) {
		returnArray[i] = new float[2];
	}

	returnArray[0][0] = factor * matrix[1][1];
	returnArray[0][1] = - factor * matrix[0][1];
	returnArray[1][0] = - factor * matrix[1][0];
	returnArray[1][1] = factor * matrix[0][0];

	return returnArray;
}

